/* eslint-disable @typescript-eslint/indent */
/* eslint-disable max-len */
/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { defineComponent, SetupContext, computed, ref, watch } from 'vue';
import { ConditionProps, conditionProps } from './condition.props';
import { Condition } from './types';
import { FDynamicFormGroup } from '../../dynamic-form';
import { useFieldConfig } from './composition/use-field-config';
import { ConditionValue } from './composition/condition-value/types';

export default defineComponent({
    name: 'FConditionFields',
    props: conditionProps,
    emits: ['valueChange', 'blur', 'focus', 'click', 'input'] as (string[] & ThisType<void>) | undefined,
    setup(props: ConditionProps, context: SetupContext) {
        const key = ref(props.key);
        const conditions = ref(props.conditions);
        const useFieldComposition = useFieldConfig(props, context);
        const { initialConditionValue, fieldMap, loadFieldConfigs } = useFieldComposition;

        loadFieldConfigs(true);

        initialConditionValue(conditions.value);

        watch(
            () => props.conditions,
            () => {
                conditions.value = props.conditions;
            }
        );

        const queryConditionClass = computed(() => ({
            row: true,
            'f-utils-flex-row-wrap': true,
            'farris-form': true,
            'farris-form-controls-inline': true
        }));

        const conditionItemClass = computed(() => {
            const classArray = ['col-12', 'col-md-6', 'col-xl-3'];
            if (conditions.value.length > 4) {
                classArray.push('col-el-2');
            }
            return classArray.join(' ');
        });

        function renderFieldConditions() {
            return conditions.value.map((condition: Condition) => (
                <FDynamicFormGroup
                    customClass={conditionItemClass.value}
                    label={condition.fieldName}
                    editor={fieldMap.get(condition.fieldCode)?.editor}
                    v-model={(condition.value as ConditionValue).value}></FDynamicFormGroup>
            ));
        }

        return () => (
            <div class={queryConditionClass.value} key={key.value}>
                {renderFieldConditions()}
            </div>
        );
    }
});
